import api from "../api/request";

// 定义API参数和返回类型
interface CreateCourseParams {
  userId: number;
  eventType: "course" | "schedule";
  name: string;
  teacher?: string;
  description?: string;
  location?: string;
  dayOfWeek: number;
  startTime: string;
  endTime: string;
  startWeek: number;
  endWeek: number;
  semester: string;
  color?: string;
  status?: 0 | 1;
}

interface UpdateCourseParams extends CreateCourseParams {
  id: number;
}

interface GetCoursesByWeekParams {
  userId: number;
  semester: string;
  week: number;
}

interface DeleteCourseParams {
  id: number;
}

// 统一响应类型
interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

// 创建课程/日程
export const createCourse = (
  data: CreateCourseParams
): Promise<
  ApiResponse<{
    id: number;
    [key: string]: any;
  }>
> => {
  return api({
    url: "/courses",
    method: "POST",
    data: {
      ...data,
      status: data.status || 1, // 默认状态为1（正常）
      color: data.color || "#5b6ee1", // 默认颜色
    },
  });
};

// 更新课程/日程
export const updateCourse = (
  data: UpdateCourseParams
): Promise<ApiResponse<Event>> => {
  if (!data.id) {
    return Promise.reject(new Error("更新课程需要提供ID"));
  }
  return api({
    url: "/courses",
    method: "PUT",
    data,
  });
};

// 获取课程/日程详情
export const getCourseById = (params: {
  id: number;
}): Promise<
  ApiResponse<{
    id: number;
    userId: number;
    eventType: "course" | "schedule";
    // 其他字段...
  }>
> => {
  return api({
    url: `/courses/${params.id}`,
    method: "GET",
  });
};

// 获取用户一周的课程/日程（带分页参数）
export const getCoursesByUserAndWeek = (
  params: GetCoursesByWeekParams & {
    page?: number;
    pageSize?: number;
  }
): Promise<
  ApiResponse<
    Array<{
      id: number;
      userId: number;
      eventType: "course" | "schedule";
      name: string;
      // 其他返回字段...
    }>
  >
> => {
  return api({
    url: "/courses/week",
    method: "GET",
    params: {
      ...params,
      page: params.page || 1,
      pageSize: params.pageSize || 50,
    },
  });
};

// 删除课程/日程（软删除）
export const deleteCourse = (
  params: DeleteCourseParams
): Promise<ApiResponse<null>> => {
  return api({
    url: `/courses/${params.id}`,
    method: "DELETE",
  });
};

// 批量获取学期数据（新增接口）
export const getSemesters = (): Promise<
  ApiResponse<
    Array<{
      id: string;
      name: string;
      startDate: string;
      endDate: string;
      weekCount: number;
    }>
  >
> => {
  return api({
    url: "/semesters",
    method: "GET",
  });
};
